﻿using UnityEngine;
using System.Collections;

public class Attack : MonoBehaviour 
{
	public float timeOfAttacks;
	public int attackDamage;

	//refrences to the player
	GameObject player;
	playerHealth playerH;

	//refrences to the enemy health
	enemyHealth enemy;

	//timer and bool to set the attack phase
	bool inRange;
	float timer;

	void Awake()
	{
		//setup refrences to the player
		player = GameObject.FindGameObjectWithTag ("soldier");
		playerH = player.GetComponent<playerHealth> ();

		//setup refrences to enemies health
		enemy = GetComponent<enemyHealth> ();

		//set the bool to false
		inRange = false;

		//set the damage 
		attackDamage = 10;
	}

	void OnTriggerEnter(Collider other)
	{
		//Debug.Log (other.name);
		//if the collider is with the player
		if(other.gameObject == player)
		{
			inRange = true;
		}
	}

	void Update()
	{
		//add to the timer
		timer += Time.deltaTime;

		//if time exceeds timeof attacks and enemy and player inRange then attack
		if(timer >= timeOfAttacks && inRange && enemy.currentHealth > 0)
		{
			attack ();
		}

		//if the player is out of health then play death scene
		if(playerH.currentHealth <= 0)
		{
			playerH.death();
		}
	}

	void attack()
	{
		//reset the time
		timer = 0f;

		//if health to loose then damage
		if(playerH.currentHealth > 0)
		{
			//damage the player
			playerH.takeDamage(attackDamage);
		}
	}
}
